$.fn.eTab = function(options) {
    return this.each(function() {
        const etab =  new ETab(this, options)
        $(this).data('etab', etab)
    })
}

/**
 * callback: {
 *     ready: () => {},
 *     onChange: () => {},
 *     onClick: () => {}
 * }
 * @param el
 * @param options
 * @constructor
 */
function ETab(el, options) {
    const no = () => {}
    const defaults = {
        callback: {
            ready: no,
            onChange: no,
            onClick: no
        }
    }

    this.$el = $(el)
    this.$head = this.$el.find('.tabs-head')
    this.$headItems = this.$el.find('.tabs-head-item')
    this.$content = this.$el.find('.tabs-content')
    this.$contentWraper = this.$el.find('.tabs-content-wrapper')
    this.$contentItem = this.$el.find('.content-item')
    this.$slider = this.$el.find('.tab-slider')

    this.options = Object.assign({}, defaults, options)
    this.init()
    this.initEvents()
}

ETab.prototype = {
    init: function() {
        const contentWidth = this.contentWidth = this.$content.width()
        this.$headItems.addClass('active')

        this.setSlider(this.$headItems.eq(0))
    },
    initEvents: function() {
        const _this = this
        this.$head.on('click', '.tabs-head-item', function () {
            const index = _this.$headItems.index($(this))
           _this.options.callback.onClick($(this))

            _this.swiperTo(index)
        })
    },
    swiperTo: function(index) {
        this.$headItems.removeClass('active')
        this.$headItems.eq(index).addClass('active')
        this.setSlider(this.$headItems.eq(index))
        this.setContent(index)

        this.options.callback.onChange && this.options.callback.onChange(this, index)
    },
    setSlider: function(menu) {
        const span = menu.find('span')
        const left = span[0].offsetLeft
        const width = span.width()
        const $bar = this.$slider

        let barWidth = width + 10

        const _left = left - (barWidth - width) / 2
        $bar.width(barWidth + 'px').animate({left: _left + 'px'}, 300)
    },
    setContent: function(index) {
        const x = -index * this.contentWidth + 'px'
        this.$contentWraper.css('transform', 'translate3d(' + x + ', 0, 0)')
    }
}